// Example 14-1. Finding contours based on a trackbar’s location; the contours are
// updated whenever the trackbar is moved

#include <iostream>
#include <opencv2/opencv.hpp>

using namespace std;

// cv::Mat g_gray, g_binary;
// int g_thresh = 100;

void on_trackbar(int thresh, void* param)
{
    const auto gray = *static_cast<cv::Mat*>(param);
    cv::Mat    g_binary;
    cv::threshold(gray, g_binary, thresh, 255, cv::THRESH_BINARY);
    vector<vector<cv::Point>> contours;
    cv::findContours(g_binary, contours, cv::RETR_LIST, cv::CHAIN_APPROX_SIMPLE);
    g_binary = cv::Scalar::all(0);

    cv::drawContours(g_binary, contours, -1, cv::Scalar::all(255));
    cv::imshow("Contours", g_binary);
}

int main(int argc, char** argv)
{
    cv::Mat g_gray;
    if (argc != 2 || (g_gray = cv::imread(argv[1], 0)).empty()) {
        cout << "\nExample 14-1: Find threshold dependent contours\nUsage:\n" << argv[0] << " ../fruits.jpg\n" << endl;
        return -1;
    }
    cv::namedWindow("Contours", 1);

    int g_thresh = 100;
    cv::createTrackbar("Threshold", "Contours", &g_thresh, 255, on_trackbar, &g_gray);
    on_trackbar(g_thresh, &g_gray);

    cv::waitKey();

    return 0;
}
